package com.wangshaoyu.music_player.controller;

import com.wangshaoyu.music_player.repository.TrackRepo;
import com.wangshaoyu.music_player.service.TrackService;
import com.wangshaoyu.music_player.session_object.UserSO;
import lombok.Data;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.List;

@RestController
@RequestMapping("/studio/track")
public class StudioTrackJsonController {
    private final TrackService trackService;
    private final TrackRepo trackRepo;

    @Autowired
    public StudioTrackJsonController(TrackService trackService, TrackRepo trackRepo) {
        this.trackService = trackService;
        this.trackRepo = trackRepo;
    }

    @Data
    public static class TrackView {
        public Integer tid;
        public String title;
        public Integer count;
    }

    @Data
    public static class TrackListView {
        public UserSO currentUser;
        public List<TrackView> trackList;
    }

    @GetMapping("/list.json")
    public TrackListView list(HttpServletRequest req) {
        TrackListView view = new TrackListView();
        HttpSession session = req.getSession(false);
        if (session != null) {
            view.currentUser = (UserSO) session.getAttribute("currentUser");
            if (view.currentUser != null) {
                view.trackList = trackService.list(view.currentUser);
            }
        }

        return view;
    }

    static class RecordView {
        public boolean result;
    }

    @PostMapping("/record.json")
    public RecordView record(HttpServletRequest request, String title, String type, @RequestBody byte[] content) {
        RecordView view = new RecordView();
        HttpSession session = request.getSession(false);
        if (session != null) {
            UserSO user = (UserSO) session.getAttribute("currentUser");
            if (user != null) {
                trackRepo.insert2(user.uid, title, type, content);
                view.result = true;
            }
        }

        return view;
    }
}
